import { store } from "@/store";
import { defineStore } from "pinia";
import * as api from "@/api/discover_api.js";
//定义用户仓库

export const musicStore = defineStore("music", {
	//定义数据源
	state: () => ({
		//歌曲地址
		musicUrl: "",
		//歌单列表
		musicList: [],
		//是否暂停
		isPause: true,
		//歌曲信息
		musicInfo: {},
		//歌手名称
		singerName: "",
	}),
	//定义方法
	actions: {
		//设置默认播放歌单第一首歌曲
		setMusicList() {
			this.musicUrl = musicList[0].url;
		},
		//上一首
		prevMusic() {
			let index = this.musicList.findIndex(
				(item) => item.al.name === this.musicInfo.name
			);
			if (index === 0) {
				index = this.musicList.length - 1;
			} else {
				index--;
			}
			console.log(index);
			api.songUrl(this.musicList[index].id, "standard").then((res) => {
				this.isPause = true;
				this.musicUrl = res.data[0].url;
				this.musicInfo = this.musicList[index].al;
				this.singerName = this.musicList[index].ar[0].name;
			});
		},
		//下一首
		nextMusic() {
			let index = this.musicList.findIndex(
				(item) => item.al.name === this.musicInfo.name
			);
			if (index === this.musicList.length - 1) {
				index = 0;
			} else {
				index++;
			}
			console.log(index);
			api.songUrl(this.musicList[index].id, "standard").then((res) => {
				this.isPause = true;
				this.musicUrl = res.data[0].url;
				this.musicInfo = this.musicList[index].al;
				this.singerName = this.musicList[index].ar[0].name;
			});
		},
		//暂停
		pauseMusic(audio) {
			this.isPause = true;
			audio.pause();
			// console.log(audio);
		},
		//播放
		playMusic(audio) {
			this.isPause = false;
			audio.play();
			// console.log(audio);
		},
	},
});
export function musicStoreWithOut() {
	return musicStore(store);
}
